package com.hllxd.hism.star.schedule;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bj58.zp.cdata.framework.rpc.client.basic.RpcInvoker;
import com.bj58.zp.cdata.framework.rpc.client.basic.RpcReqData;
import com.bj58.zp.cdata.framework.rpc.client.basic.RpcResData;
import com.hllxd.hism.star.util.SyslogManager;
import com.hllxd.hism.star.util.Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author xiyong.lxy
 * @date 2018-11-02 09:10
 * 通过定时 上报拦截到请求
 */
@Slf4j
@Component
public class SyslogTasker {

    @Autowired
    private RpcInvoker rpcInvoker;


    public static final String SYSLOG_USER = "star.web";
    public static final String SYSLOG_SERVICE = "basic-service";
    public static final String SYSLOG_PATH = "/v1/syslog_log/setSyslogEntity.do";

    /**
     * 频次：每1分钟执行一次
     * 针对新建的支持组生成排班计划
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void schedRg() throws Exception {
        long startTs = System.currentTimeMillis();
        List<Object> datas = SyslogManager.consume();
        if(datas==null || datas.size()==0) {
            return;
        }
        String retCode = reportSyslogRequest(datas);
        long endTs = System.currentTimeMillis();
        log.info("code: {}, report size: {}, process:{}, .",retCode, datas.size(), endTs - startTs);
    }
    private String reportSyslogRequest(List<Object> datas) {
        JSONObject obj = new JSONObject();
        obj.put("items", JSON.toJSONString(datas));
        String traceID = Utils.getTraceID();
        RpcReqData reqData = buildRpcReqData(traceID, SYSLOG_USER, SYSLOG_PATH, obj.toString());
        try {
            RpcResData<String> rpcResData = rpcInvoker.invoke(SYSLOG_SERVICE, reqData);
            if (rpcResData == null) {
                return "002";
            }
            return rpcResData.getCode();
        }catch (Exception e) {
            log.error("exception failed. {}.",e.toString());
            return "001";
        }
    }
    private static RpcReqData buildRpcReqData(String traceID, String userID, String path, String params) {
        RpcReqData thiz = new RpcReqData();
        thiz.setTraceID(traceID);
        thiz.setUserID(userID);
        thiz.setPath(path);
        thiz.setData(JSON.parse(params));
        return thiz;
    }
}
